# 下载JavaScript库文件用于离线使用
param(
    [switch]$Force
)

$ErrorActionPreference = "Stop"
$jsDir = Join-Path $PSScriptRoot "Resources\js"

# 确保目录存在
if (-not (Test-Path $jsDir)) {
    New-Item -ItemType Directory -Path $jsDir | Out-Null
}

# 库文件配置
$libraries = @(
    @{
        Name = "marked.min.js"
        Urls = @(
            "https://cdn.jsdelivr.net/npm/marked@11.0.0/marked.min.js",
            "https://unpkg.com/marked@11.0.0/marked.min.js",
            "https://cdnjs.cloudflare.com/ajax/libs/marked/11.0.0/marked.min.js"
        )
    },
    @{
        Name = "mermaid.min.js"
        Urls = @(
            "https://cdn.jsdelivr.net/npm/mermaid@10.6.1/dist/mermaid.min.js",
            "https://unpkg.com/mermaid@10.6.1/dist/mermaid.min.js"
        )
    }
)

Write-Host "=== JavaScript库下载工具 ===" -ForegroundColor Cyan
Write-Host ""

foreach ($lib in $libraries) {
    $targetFile = Join-Path $jsDir $lib.Name
    
    # 检查文件是否已存在
    if ((Test-Path $targetFile) -and -not $Force) {
        Write-Host "[跳过] $($lib.Name) 已存在" -ForegroundColor Yellow
        continue
    }
    
    Write-Host "[下载] $($lib.Name)..." -ForegroundColor Cyan
    $downloaded = $false
    
    foreach ($url in $lib.Urls) {
        try {
            Write-Host "  尝试: $url" -ForegroundColor Gray
            Invoke-WebRequest -Uri $url -OutFile $targetFile -TimeoutSec 30
            $fileSize = (Get-Item $targetFile).Length
            Write-Host "  ✓ 成功! ($('{0:N0}' -f $fileSize) bytes)" -ForegroundColor Green
            $downloaded = $true
            break
        }
        catch {
            Write-Host "  ✗ 失败: $($_.Exception.Message)" -ForegroundColor Red
        }
    }
    
    if (-not $downloaded) {
        Write-Host "  [错误] 所有CDN都无法下载 $($lib.Name)" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "=== 下载完成 ===" -ForegroundColor Green
Write-Host ""
Write-Host "提示:" -ForegroundColor Yellow
Write-Host "  - 库文件保存在: Resources\js\" -ForegroundColor White
Write-Host "  - 应用将优先使用本地文件" -ForegroundColor White
Write-Host "  - 如需重新下载，使用: .\DownloadLibs.ps1 -Force" -ForegroundColor White
Write-Host ""

# 显示已下载的文件
Write-Host "已下载的文件:" -ForegroundColor Cyan
Get-ChildItem $jsDir -File | ForEach-Object {
    $size = '{0:N0}' -f $_.Length
    Write-Host "  ✓ $($_.Name) ($size bytes)" -ForegroundColor Green
}

